import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  const env = loadEnv(mode, process.cwd())

  return {
    base: './',
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'), // 设置 @ 指向 src 目录
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 全局变量已经在各个文件中通过 @use 引入
        },
      },
    },
    plugins: [
      vue(),
      // ElementPlus 组件和 API 自动导入
      AutoImport({
        resolvers: [ElementPlusResolver()],
        imports: ['vue', 'vue-router', 'pinia'], // 自动导入 Vue、Vue Router、Pinia 相关 API
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      // SVG 图标插件配置
      createSvgIconsPlugin({
        iconDirs: [resolve(__dirname, 'src/assets/icons')], // 指定需要缓存的图标文件夹
        symbolId: 'icon-[dir]-[name]', // 指定 symbolId 格式
      }),
    ],
    server: {
      host: '0.0.0.0',
      port: 3333,
      open: true,
      proxy: {
        '/api': {
          target: env.VITE_PROXY_TARGET,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '/api')
        },
        // 图片代理
        "^/simulation/": {
          // target: 'http://172.19.7.40:12001/', // 张亚超
          target: "https://172.25.7.210/api/", // 演示环境
          // target: 'http://172.19.5.197:12001', // 许超
          // target: 'http://172.17.0.181:12001', // 恒哥
          // target: 'http://172.19.6.166:12001', // 浩磊
          changeOrigin: true,
          secure: false,
        },
      }
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      // 生产环境移除 console 和 debugger
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      // 分割大文件
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            vue: ['vue', 'vue-router', 'pinia'],
            elementPlus: ['element-plus'],
          },
        },
      },
    },
  }
})
